<template>
  <div class="view">
    <ObjectView
      key-name="config"
      :value="config"
      @change="change"
      parent-key="config"
      :isSelect="isSelect"
    ></ObjectView>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { socket, getConfig, setConfig } from "../init";
import { Config } from "../typing";
import ObjectView from "./componet/object.vue";

@Component({
  components: { ObjectView }
})
export default class ConfigView extends Vue {
  public config: any = {};

  constructor(...args: any) {
    super(...args);
    getConfig().then((config: Config) => {
      for (const key in config) {
        this.$set(this.config, key, config[key]);
      }
    });
  }

  public change(keys: string, value: any) {
    let target: any = this;
    const list = keys.split(".");
    const lastKey = list.pop();
    if (lastKey) {
      for (const key of list) {
        target = target[key]
      }
      target[lastKey] = value;
      setConfig(JSON.stringify(this.config, null, 4));
    }
  }

  public isSelect(name: string) {
    if (/\.remote_versions\.(.+?)/.test(name)) {
      return (serviceName: string, callback: (tags: string[]) => void) => {
        socket.wsCallback({
            type: "getConsulNodeTags",
            serviceName
          }, (result) => {
            callback(result.tags);
          }
        );
      };
    }
  }
}
</script>

<style scoped>
.view {
  width: 100%;
  padding: 10px;
  overflow: auto;
}
</style>